﻿using System;
using System.Security.Cryptography;
using System.Text;

namespace ThresholdAssistant.Tools
{
    /// <summary>
    /// Md5加密工具类
    /// </summary>
    public class Md5Encryption
    {
        /// <summary>
        /// 32位MD5加密
        /// </summary>
        /// <param name="content"></param>
        /// <param name="lowercase"></param>
        /// <returns></returns>
        public static string Md5Hash(string content, bool lowercase = true)
        {
            using var md5Provider = new MD5CryptoServiceProvider();
            byte[] data = md5Provider.ComputeHash(Encoding.UTF8.GetBytes(content));
            string hash = BitConverter.ToString(data);
            hash = hash.Replace("-", string.Empty);
            if (lowercase)
            {
                return hash.ToLower();
            }
            return hash;
        }

        /// <summary>
        /// 获取字符串的MD5
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public static string GetMD5String(string content)
        {
            MD5 md5 = MD5.Create();
            byte[] bytes = Encoding.UTF8.GetBytes(content);
            byte[] data2 = md5.ComputeHash(bytes);
            return GetbyteToString(data2);
        }

        /// <summary>
        /// byte数组转换成十六进制字符串
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        private static string GetbyteToString(byte[] bytes)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < bytes.Length; i++)
            {
                sb.Append(bytes[i].ToString("x2"));
            }
            return sb.ToString();
        }
    }
}